package com.cloudm.technician.ui.modules.web

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.cloudm.technician.R
import com.cloudm.technician.ui.base.BaseFragment
import com.cloudm.technician.ui.base.BasePresenter

/**
 * 作者: wesley
 * 时间: 2017/12/28
 * 描述: ui
 */
class WebFragment : BaseFragment<BasePresenter>() {

    private var url: String? = null
    private var webView: WebView? = null
    var listener: OnTitleReceivedListener? = null

    override val resource: Int
        get() = R.layout.fragment_web

    companion object {
        fun newInstance(url: String?) = WebFragment().apply {
            arguments = Bundle().apply {
                putString("url", url)
            }
        }
    }

    override fun initInject() {

    }

    override fun handleBundle(bundle: Bundle) {
        url = bundle.getString("url")
    }

    override fun initVariables() {

    }

    override fun initViews(view: View) {
        webView = view.findViewById(R.id.webView)
        initWebView()
    }

    override fun initListener() {

    }

    @SuppressLint("SetJavaScriptEnabled") private fun initWebView() {
        webView?.webViewClient = InstallWebViewClient()
        webView?.webChromeClient = InstallWebChromeClient()
        webView?.settings?.javaScriptEnabled = true
        webView?.loadUrl(url)
    }

    private class InstallWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?,
                                              request: WebResourceRequest?): Boolean {
            return true
        }
    }

    private inner class InstallWebChromeClient : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            listener?.onTitleReceive(title ?: "")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        webView?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        webView?.clearHistory()
        val viewGroup = webView?.parent as? ViewGroup ?: return
        viewGroup.removeView(webView)
        webView?.destroy()
        webView = null
    }

    fun canGoBack(): Boolean {
        return webView?.canGoBack() ?: false
    }

    fun goBack() {
        webView?.goBack()
    }


    interface OnTitleReceivedListener {

        fun onTitleReceive(title: String)
    }
}